# 动态柱状图
from pyecharts.charts import Bar,Timeline
from pyecharts.options import *
from pyecharts.globals import ThemeType

# 1. 处理文件中的数据，获取原始数据
def get_origin_data(file_name:str):
    with open(file_name,'r',encoding='gbk') as f:
        file_lines=f.readlines()
        file_lines.pop(0)

        year_gdp_dict=dict()
        for line in file_lines:
            cell_list=line.split(",")
            year=int(cell_list[0])
            country=cell_list[1]
            gdp=round(float(cell_list[2])/10**8,2)
            if not (year in year_gdp_dict):
                # print(f"{year}年份数据不存在,{not (year in year_gdp_dict)}")
                year_gdp_dict[year]=[]
                # print(year in year_gdp_dict)
            year_gdp_dict[year].append((country,gdp))
        for year in year_gdp_dict.keys():
            year_gdp_dict[year].sort(key=lambda ele:ele[1],reverse=True)
        return year_gdp_dict


# 2. 构建动态柱状图所需要的数据
def convert_graph_data(origin_data:dict,top_len:int):
    year_list=sorted(origin_data.keys())
    result=[]
    for year in year_list:
        gdp_list=origin_data[year][:top_len]
        gdp_list.sort(key=lambda ele:ele[1])
        x_data=[]
        y_data=[]
        for cell in gdp_list:
            x_data.append(cell[0])
            y_data.append(cell[1])
        result.append((year,x_data,y_data))
    return result

# 3. 构建动态柱状图
def build_timeline(data:list):
    timeline=Timeline({"theme":ThemeType.LIGHT})
    for row in data:
        year=row[0]
        x_data=row[1]
        y_data=row[2]
        bar=Bar()
        bar.add_xaxis(x_data)
        bar.add_yaxis("GDP(亿)",y_data,label_opts=LabelOpts(position="right"))
        bar.reversal_axis()

        timeline.add(bar,str(year))
    timeline.add_schema(
        play_interval=1000,
        is_auto_play=True,
        is_timeline_show=True,
        is_loop_play=True
    )
    timeline.render("../output/1960-2019全球GDP数据TOP8.html")

if __name__=="__main__":
    origin_data=get_origin_data("../static/1960-2019全球GDP数据.csv")
    # print(origin_data)
    data=convert_graph_data(origin_data,8)
    build_timeline(data)